$(function () {
  var form = layui.form;
  initArtCate();
  function initArtCate() {
    $.ajax({
      url: "/my/article/cates",
      method: "get",
      success: function (res) {
        if (res.status !== 0) {
          return layer.msg(res.message);
        }
        // console.log(res);
        var htmlStr = template("tpl", res);
        $("tbody").html(htmlStr);
      },
    });
  }
  //关闭弹出层
  var layerIndex = null;
  // 添加类别
  $("#addBtn").on("click", function () {
    // alert(1);
    //搞一个弹框
    layerIndex = layer.open({
      type: 1,
      title: "添加文章分类",
      area: ["500px", "250px"],
      content: $("#tplAddCate").html(),
    });

    //给表单绑定事件
    $("body").on("submit", "#addCateForm", function (e) {
      e.preventDefault();
      $.ajax({
        url: "/my/article/addcates",
        method: "post",
        data: $(this).serialize(),
        success: function (res) {
          if (res.status !== 0) {
            return layer.msg(res.message);
          }
          layer.msg("添加成功哈!");
          initArtCate();
          layer.close(layerIndex);
        },
      });
    });
  });
  // 编辑文章
  $("tbody").on("click", "#editBtn", function () {
    // alert(1);
    //搞一个弹框
    layerIndex = layer.open({
      type: 1,
      title: "修改文章分类",
      area: ["500px", "250px"],
      content: $("#tplEditCate").html(),
    });
    var cate_id = $(this).attr("data-id");
    console.log(cate_id);
    $.ajax({
      method: "get",
      url: "/my/article/cates/" + cate_id,

      success: function (res) {
        console.log(res);
        if (res.status !== 0) {
          return layer.msg(res.message);
        }
        layer.msg("获取表单内容成功哈！");
        // 快速给表单赋值
        form.val("editCateForm", res.data);
      },
    });
  });
  // 提交编辑更新文章内容
  $("body").on("submit", "#editCateForm", function (e) {
    e.preventDefault();
    $.ajax({
      method: "post",
      url: "/my/article/updatecate",
      data: $(this).serialize(),
      success: function (res) {
        console.log(res);
        if (res.status !== 0) {
          return layer.msg(res.message);
        }
        layer.msg("更改成功");
        initArtCate();
        layer.close(layerIndex);
      },
    });
  });
  //利用事件委托给删除按钮
  $("tbody").on("click", "#btnDel", function () {
    console.log("删除");
    var id = $(this).attr("data-id");
    //设置一个弹出层
    layer.confirm("确认删除吗?", { icon: 3, title: "提示" }, function (index) {
      //do something
      $.ajax({
        url: "/my/article/deletecate/" + id,
        method: "get",
        success: function (res) {
          if (res.status !== 0) {
            return layer.msg(res.message);
          }
          layer.msg("删除成功");
          initArtCate();
        },
      });

      layer.close(index);
    });
  });
});
